package com.example.Laboratory.Service.Impl;

import com.example.Laboratory.Entity.Carousel;
import com.example.Laboratory.Mapper.CarouselMapper;
import com.example.Laboratory.Service.CarouselService;
import com.example.Laboratory.Untils.FileUtil;
import com.example.Laboratory.Untils.OperationFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

//轮播图
@Service
public class CarouselServiceImpl implements CarouselService {

    @Autowired
    CarouselMapper carouselMapper;


    //查询轮播图
    @Override
    public Object researchCarousel() {
        return carouselMapper.SeAll();
    }

    //添加轮播图
    @Override
    public String addCarousel(int carousel_level, MultipartFile File) {
        if (carouselMapper.researchNumber() < 3 && carouselMapper.researchLevel(carousel_level) == null) {
            String path = OperationFile.upfile(File);
            if (path.equals("文件已存在")) {
                return path;
            } else if (path.equals("没有选择文件")) {
                return path;
            } else {
                Carousel carousel = new Carousel();
                carousel.setCarousel_address(path);
                carousel.setCarousel_level(carousel_level);
                carouselMapper.addCarousel(carousel);
                return "上传成功";
            }
        }else {
            return "图片超过三张或顺序重复";
        }
    }


    //修改轮播图
    @Override
    public String reviseCarouselLevel(int carousel_id, int carousel_level,MultipartFile File) {
        if (carouselMapper.researchLevel(carousel_level) == null) {
            String filepath = carouselMapper.researchAddress(carousel_id);
            String tip = OperationFile.updatafile(filepath, File);
            if (tip.equals("文件已存在")) {
                return tip;
            } else if (tip.equals("没有选择文件")) {
                return tip;
            } else if (tip.equals("更新失败")){
                return tip;
            } else {
                Carousel carousel = new Carousel();
                carousel.setCarousel_address(tip);
                carousel.setCarousel_id(carousel_id);
                carousel.setCarousel_level(carousel_level);
                carouselMapper.reviseCarousel(carousel);
                return "修改成功";
            }
        } else {
            return "";
        }
    }

    //删除轮播图图片
    @Override
    public String deleteCarousel(int carousel_id) {
        //获取文件名称,包含后缀
        String filepath = carouselMapper.researchAddress(carousel_id);
        int code = OperationFile.deletefile(filepath);
        if (code == 1) {
            carouselMapper.deleteCarousel(carousel_id);
            return "删除成功";
        } else if (code == 0) {
            return "删除失败";
        } else if (code == 2) {
            return "文件不存在";
        } else {
            return "发生未知错误";
        }

    }
}

